package com.lovepick.database;

import java.util.ArrayList;
import java.util.List;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.lovepick.bean.MsgItem;
import com.lovepick.util.MsgType;
/**
 * @author Liutong
 *
 * <p>
 * 根据会话对象ID分别为每个对象创建一张表,
 * 保存当前用户与该会话对象的会话记录
 * <p>
 *
 */
public class MsgDbManager
{
	private static final String TAG = "MsgDbManager";
	private SQLiteDatabase mDatabase = null;
	private DatabaseHelper mDbHelper = null;
	private final String CREATE_TABLE_SQL = "CREATE TABLE IF NOT EXISTS _";
	private final String TABLE_STRUCTURE = " ("
			+ MsgTable.ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
			+ MsgTable.CONTENT + " TEXT, "
			+ MsgTable.DATE + " TEXT, "
			+ MsgTable.MSG_TYPE + " INTEGER"
			+ ");";

	public MsgDbManager()
	{
		mDbHelper = new DatabaseHelper();
	}

	/**
	 * <p>为会话对象创建表, 存储消息记录.<p>
	 *
	 * @param userID	会话对象的ID
	 */
	private void create(int userID)
	{
		////Log.i(TAG, "-----create-----");
		String sql = CREATE_TABLE_SQL + userID + TABLE_STRUCTURE;
		////Log.i(TAG, "###sql###");
		////Log.i(TAG, sql);
		mDatabase.execSQL(sql);
	}

	/**
	 * 为会话对象userID插入一条消息记录
	 *
	 * @param userID	会话对象ID
	 * @param msgItem	消息内容
	 */
	private void add(int userID, MsgItem msgItem)
	{
		////Log.i(TAG, "-----add-----");
		int msgType = ((MsgType.SEND.equals(msgItem.getMsgType())) ? 0 : 1);
		String insertSql = "INSERT INTO _" + userID
				+ " ("
				+ MsgTable.CONTENT + ","
				+ MsgTable.DATE + ","
				+ MsgTable.MSG_TYPE
				+ ")"
				+ " VALUES "
				+ "(?,?,?);";
		Object[] bindArgs = new Object[]{msgItem.getContent(), msgItem.getDate(), msgType};
		mDatabase.execSQL(insertSql, bindArgs);
	}

	/**
	 * 为会话对象useID插入一条消息记录
	 *
	 * @param userID	会话对象ID
	 * @param msgItem	消息内容
	 */
	public void addMsg(int userID, MsgItem msgItem)
	{
		////Log.i(TAG, "-----addMsg-----");
		try
		{
			mDatabase = mDbHelper.getWritableDatabase();
			create(userID);
			add(userID, msgItem);
			mDatabase.close();
		}
		catch (Exception e)
		{
			// TODO Auto-generated catch block
			Log.e(TAG, "Exception");
			e.printStackTrace();
		}
	}

	/**
	 * 为会话对象userID插入多条消息
	 *
	 * @param userID	会话对象ID
	 * @param msgItems	消息列
	 */
	public void addMsgs(int userID, List<MsgItem> msgItems)
	{
		////Log.i(TAG, "-----addMsgs-----");
		try
		{
			mDatabase = mDbHelper.getWritableDatabase();
			create(userID);
			if (msgItems != null)
			{
				for (MsgItem msgItem : msgItems)
				{
					add(userID, msgItem);
				}
			}
			mDatabase.close();
		}
		catch (NullPointerException e)
		{
			// TODO Auto-generated catch block
			Log.e(TAG, "NullPointerException");
			e.printStackTrace();
		}
		catch (Exception e)
		{
			// TODO: handle exception
			Log.e(TAG, "Exception");
			e.printStackTrace();
		}
	}

	/**
	 * 根据会话对象ID获取消息列表
	 *
	 * @param userID	会话对象ID
	 * @return	消息列表
	 */
	public List<MsgItem> getMsgItems(int userID)
	{
		//Log.i(TAG, "-----getMsgItems-----");
		List<MsgItem> msgItems = null;
		boolean cursorNull = true;
		try
		{
			mDatabase = mDbHelper.getWritableDatabase();
			create(userID);
			msgItems = new ArrayList<MsgItem>();
			String selectSql = "SELECT * FROM _" + userID + " ORDER BY " + MsgTable.DATE + " ASC;";
			Cursor cursor = mDatabase.rawQuery(selectSql, null);
			while (cursor.moveToNext())
			{
				cursorNull = false;
				MsgItem msgItem = new MsgItem();
				msgItem.setMsgId(cursor.getInt(cursor.getColumnIndex(MsgTable.ID)));
				msgItem.setContent(cursor.getString(cursor.getColumnIndex(MsgTable.CONTENT)));
				msgItem.setDate(cursor.getString(cursor.getColumnIndex(MsgTable.DATE)));
				int type = cursor.getInt(cursor.getColumnIndex(MsgTable.MSG_TYPE));
				MsgType msgType = ((0 == type) ? MsgType.SEND : MsgType.RECEIVE);
				msgItem.setMsgType(msgType);
				msgItems.add(msgItem);
			}
			if (cursorNull)
			{
				msgItems = null;
			}
			cursor.close();
			mDatabase.close();
		}
		catch (NullPointerException e)
		{
			//Log.i(TAG, "NullPointerException");
			e.printStackTrace();
			msgItems = null;
		}
		catch (Exception e)
		{
			// TODO Auto-generated catch block
			Log.e(TAG, "Exception");
			e.printStackTrace();
			msgItems = null;
		}
		return msgItems;
	}


	/**
	 * 根据会话对象ID获取消息列表
	 *
	 * @param userID	会话对象ID
	 * @return	消息列表
	 */
	public List<MsgItem> getMsgItemsField(int userID, int last)
	{
		//Log.i(TAG, "-----getMsgItems-----");
		List<MsgItem> msgItems = null;
		boolean cursorNull = true;
		try
		{
			mDatabase = mDbHelper.getWritableDatabase();
			create(userID);
			msgItems = new ArrayList<MsgItem>();
			String selectSql = "SELECT * FROM _" + userID
					+ " WHERE "
					+ MsgTable.ID
					+ ">" + last
					+" ORDER BY " + MsgTable.DATE + " ASC;";
			//Log.i(TAG, selectSql);
			Cursor cursor = mDatabase.rawQuery(selectSql, null);
			while (cursor.moveToNext())
			{
				cursorNull = false;
				MsgItem msgItem = new MsgItem();
				msgItem.setMsgId(cursor.getInt(cursor.getColumnIndex(MsgTable.ID)));
				msgItem.setContent(cursor.getString(cursor.getColumnIndex(MsgTable.CONTENT)));
				msgItem.setDate(cursor.getString(cursor.getColumnIndex(MsgTable.DATE)));
				int type = cursor.getInt(cursor.getColumnIndex(MsgTable.MSG_TYPE));
				MsgType msgType = ((0 == type) ? MsgType.SEND : MsgType.RECEIVE);
				msgItem.setMsgType(msgType);
				msgItems.add(msgItem);
			}
			if (cursorNull)
			{
				msgItems = null;
			}
			cursor.close();
			mDatabase.close();
		}
		catch (NullPointerException e)
		{
			//Log.i(TAG, "NullPointerException");
			e.printStackTrace();
			msgItems = null;
		}
		catch (Exception e)
		{
			// TODO Auto-generated catch block
			Log.e(TAG, "Exception");
			e.printStackTrace();
			msgItems = null;
		}
		return msgItems;
	}

	public int getMsgNum(int userID)
	{
		//Log.i(TAG, "-----getMsgNum-----");
		int count = 0;
		try
		{
			mDatabase = mDbHelper.getWritableDatabase();
			create(userID);
			String selectSql = "SELECT * FROM _" + userID + " ORDER BY " + MsgTable.DATE + " ASC;";
			Cursor cursor = mDatabase.rawQuery(selectSql, null);
			count = cursor.getCount();
			mDatabase.close();
		}
		catch (Exception e)
		{
			// TODO Auto-generated catch block
			Log.e(TAG, "Exception:" + e.getCause());
			e.printStackTrace();
			count = 0;
		}

		return count;

	}

	public void deleteMsgItem(int userID, MsgItem item)
	{
		//Log.i(TAG, "-----deleteMsgItem-----");
		String deleteSql = "DELETE FROM _" + userID
				+ " WHERE "
				+ MsgTable.ID
				+ "="
				+ item.getMsgId();
		try
		{
			mDatabase = mDbHelper.getWritableDatabase();
			//Log.i(TAG, deleteSql);
			mDatabase.execSQL(deleteSql);
			mDatabase.close();
		}
		catch (Exception e)
		{
			// TODO: handle exception
			Log.e(TAG, "Exception:" + e.getCause());
			e.printStackTrace();
		}
	}

	public void deleteMsgItems(int userID, List<MsgItem> items)
	{
		//Log.i(TAG, "-----deleteMsgItems-----");
		String deleteSql = "";
		try
		{
			mDatabase = mDbHelper.getWritableDatabase();
			for (MsgItem msgItem : items)
			{
				deleteSql = "DELETE FROM _" + userID
						+ " WHERE "
						+ MsgTable.ID
						+ "="
						+ msgItem.getMsgId();
				//Log.i(TAG, deleteSql);
				mDatabase.execSQL(deleteSql);
			}

			mDatabase.close();
		}
		catch (Exception e)
		{
			// TODO: handle exception
			Log.e(TAG, "Exception:" + e.getCause());
			e.printStackTrace();
		}
	}

	public void deleteMsgAll(int userID)
	{
		//Log.i(TAG, "-----deleteMsgAll-----");
		String dropSql = "DROP TABLE IF EXISTS _" + userID;
		String delSql = "DELETE FROM " + MsgListTable.TABLE_NAME
				+ " WHERE "
				+ MsgListTable.USER_ID
				+ "="
				+ userID;
		try
		{
			mDatabase = mDbHelper.getWritableDatabase();
			mDatabase.execSQL(dropSql);
			mDatabase.execSQL(delSql);
			mDatabase.close();
		}
		catch (Exception e)
		{
			// TODO: handle exception
			Log.e(TAG, "Exception:" + e.getCause());
			e.printStackTrace();
		}
	}
}
